from django.shortcuts import render, redirect, HttpResponse
from rbac import models
from rbac.service.init_permission import initial_permission
from pro_cmdb.forms import LoginForm, AddEditHostsForm, CallCircuitForm
from pro_cmdb.models import CallCircuit,Hosts
from tools.paginator import Pagination
from tools.response import BaseResponse
import json

# Create your views here.


def login(request):
    '''
    登陆
    :param request: 
    :return: 
    '''
    if request.method == "GET":
        form = LoginForm()
        return render(request, "cmdb/login.html", {"form":form})
    elif request.method == "POST":
        form = LoginForm(data=request.POST)
        if form.is_valid():
            user = models.UserInfo.objects.filter(**form.cleaned_data).first()
            if user:
                initial_permission(request, user)
                request.session['UserName'] = user.username
                request.session['Uid'] = user.id
                return render(request, 'cmdb/index.html')
            else:
                # 登录失败，主动提示错误
                # form.add_error("password", "用户名或密码错误")
                from django.core.exceptions import ValidationError
                form.add_error("password", ValidationError('用户名或密码错误'))
        return render(request, 'cmdb/login.html', {'form': form})

def index(request):
    '''
    首页
    :param request: 
    :return: 
    '''
    return render(request, 'cmdb/index.html')

def hosts(request):
    '''
    主机管理
    :param request: 
    :return: 
    '''
    res = BaseResponse()
    if request.method == "GET":
        all_hosts_list = Hosts.objects.all()

        #分页功能
        all_hosts_count = all_hosts_list.count()
        current_page = request.GET.get('page')
        # print(request.get_full_path(), request.GET.get('nid'))
        # 将带页码的URL写入session，以便以后调用
        request.session['get_url'] = "/cmdb/hosts/?page={}".format(
            current_page) if current_page else "/cmdb/hosts/?page=1"
        page_obj = Pagination(current_page, all_hosts_count, '/cmdb/hosts/')
        host_list = all_hosts_list[page_obj.start:page_obj.end]
        page_str = page_obj.page_html()
        if page_str:
            res.status = True
            res.data = {"host_list": host_list, "page_str":page_str}
        else:
            res.msg = "无数据,请添加!"
    return render(request, 'cmdb/hosts.html', res.get_dict)

def logout(request):
    '''
    注销登录
    :param request: 
    :return: 
    '''
    request.session.clear()
    # print('Logout', request.session.get('UserName'))
    return redirect('login')

def addhost(request):
    '''
    添加host
    :param request: 
    :return: 
    '''
    res = BaseResponse()
    get_url = request.session['get_url']
    if request.method == "GET":
        form = AddEditHostsForm()
        res.status = True
        res.data = {"form": form, "title": "添加主机表"}
        print(res.get_dict)
        return render(request, 'cmdb/addedithost.html', res.get_dict)
    elif request.method == "POST":
        form = AddEditHostsForm(data=request.POST)
        if form.is_valid():
            Hosts.objects.create(**form.cleaned_data)
            return redirect(get_url)
        else:
            return render(request, 'cmdb/addedithost.html', {'form': form})


def edithost(request, hid=None):
    '''
    修改host
    :param request: 
    :return: 
    '''
    print(hid, request.GET)
    res = BaseResponse()
    get_url = request.session['get_url']
    hid = hid if hid else request.GET.get('hid')
    if request.method == "GET":
        obj = Hosts.objects.filter(id=hid).first()
        form = AddEditHostsForm(initial={"Name": obj.Name,
                                "IP": obj.IP,
                                "CPU": obj.CPU,
                                "Mem": obj.Mem,
                                "callCircuit_id": obj.callCircuit_id
                                 })
        res.status = True
        res.data = {"form":form, "title":"修改主机表"}
        return render(request, 'cmdb/addedithost.html', res.get_dict)
    elif request.method == "POST":
        form = AddEditHostsForm(data=request.POST)
        if form.is_valid():
            obj = Hosts.objects.filter(id=hid)
            obj.update(**form.cleaned_data)
            return redirect(get_url)
        else:
            return render(request, 'cmdb/addedithost.html', {'form': form})



def delhost(request):
    '''
    删除host
    :param request: 
    :return: 
    '''

    get_url = request.session['get_url']
    if request.method == "POST":
        res = BaseResponse()
        pk = request.POST.get('id')
        obj = Hosts.objects.filter(id=pk)
        if obj:
            obj.delete()
            res.status = True
            res.data = {'id': int(pk)}
        else:
            res.msg = "数据库中没有找到该条目，请联系管理员"
        return HttpResponse(json.dumps(res.get_dict))
    return redirect(get_url)
